<?php
App::uses('CakeEmail', 'Network/Email');
App::uses('CakeTime','Utility');

class UsersController extends AppController {
	var $components = array(
		'Auth'=> array(
			'allowedActions' => array('login','register','logout',
			'forgotten_password','forgotten_credentials'),
			'loginAction' => array(
				'controller' => 'users',
				'action' => 'login'
				),
			'logoutAction' =>array(
				'controller' => 'users',
				'action' => 'logout'
			)
		),'BagabEmail'
	);
	
	/** @TODO **/
	public function forgotten_credentials(){
		$this->set('subtitle','Avez-vous oubli&eacute; vos identifiants?');
		$this->set('paragraph_for_subtitle','En saisissant votre adresse email ci-dessous, nous nous chargerons de vous fournir les moyens de vous connecter &agrave; nouveau.');
		if(!empty($this->data)){
			$user = $this->getUserFromEmail($this->data['User']['email']);
			if($user){
				//Send an Email
				$this->BagabEmail->sendCredentials(
					$user['User']['email'],
					$user['User']['username'],
					$user['User']['password']
				);
			}
		}
	}
	
	/** @TODO **/
	public function forgotten_password(){
		$this->set('subtitle','Avez-vous oubli&eacute; votre mot de passe?');
		$this->set('paragraph_for_subtitle','En saisissant votre adresse email ci-dessous, nous nous chargerons de vous fournir les moyens de vous connecter &agrave; nouveau.');
		if(!empty($this->data)){
			$user = $this->getUserFromEmail($this->data['User']['email']);
			if($user){
			//Send an Email
			$this->BagabEmail->sendPassword(
					$user['User']['email'],
					$user['User']['password']
				);
			}
		}
	}
	
	/** @TODO **/
	public function index(){
				
	}
	
	function login() {
		$this->set('subtitle','Connectez-vous');
		$this->set('paragraph_for_subtitle','Connectez-vous pour faciliter vos commandes.');
		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
				$this->User->read(null, $this->Auth->User('id'));
				$this->User->set('lastlogin',CakeTime::format('Y-m-d H:i:s',date('Y-m-d H:i:s'),false,new DateTimeZone('Europe/Paris')));
				$this->User->save();
				return $this->redirect($this->Auth->redirect());
			} else {
				$this->set('error_for_layout',array('D&eacute;sol&eacute; votre nom d\'utilisateur ou mot de passe est invalide.'));
				return;
			}
		}
	}
	
	public function logout(){
		$this->redirect($this->Auth->logout());
	}
	
	public function register(){
		$this->set('isNewCustomer', true);
		$this->set('subtitle','Enregistrez-vous');
		$this->set('paragraph_for_subtitle','Saisissez vos donn&eacute;es et nous les garderons pour vous faciliter la t&acirc;che.');
		$this->Auth->logout();
		if (!empty($this->data)) {
			if($this->data['User']['password'] == $this->data['User']['password_confirm']){
				$this->request->data['User']['accountcreationdate'] = CakeTime::format('Y-m-d H:i:s',date('Y-m-d H:i:s'),false,new DateTimeZone('Europe/Paris'));
				$this->request->data['User']['lastlogin'] = CakeTime::format('Y-m-d H:i:s',date('Y-m-d H:i:s'),false,new DateTimeZone('Europe/Paris'));
				$this->User->create();
				if ($this->User->saveAll($this->data)) {
					$id = $this->User->id;
					$this->request->data['User'] = array_merge($this->request->data['User'], array('id' => $id));
					$this->Auth->login($this->request->data['User']);
					$this->redirect(array('controller'=>'products','action'=>'index'));
				}
			}else
			{
			$register_error[] = "";
			}
		}
	}
	
	/** @TODO **/
	public function delete(){
	
	}
	
	/** @TODO **/
	public function edit($id = null){
		$this->set('isNewCustomer', false);
		$this->set('subtitle','Editez votre profil');
		$this->set('paragraph_for_subtitle','Saisissez vos donn&eacute;es et nous les garderons pour vous faciliter la t&acirc;che.');
		if(!empty($this->data)){
			if($this->data['User']['password'] == $this->data['User']['password_confirm']){
				
				if($this->User->saveAll($this->data)) {
					$this->Session->write('Auth', $this->User->read(null, $this->Auth->User('id')));
					$this->redirect(array('controller'=>'products','action'=>'index'));
				}else{
					//Erreur lors de la modification de l'utilisateur
					$this->set('error_for_layout',array('Il y a eu une erreur, pourriez-vous r&eacute;essayer?'));
					$this->render('register');				
				}
			}else{
				$this->set('error_for_layout',array('Les mots de passes entr&eacute; sont diff&eacute;rents.'));
				$this->render('register');	
			}
		}else{
			$userId = $this->Session->read('Auth.User.id');
			$this->request->data = $this->User->findAllById($userId)[0];
			$this->request->data['User']['password']='';
			$this->render('register');
		}		
	}
	
	private function getUserFromEmail($email){
			$current_user = $this->User->findByEmail($email);
			if($current_user == null){
				return false;
			}
			return $current_user;
	}
}